<?php

namespace DebugComponent\Plugin;

class Database implements \DebugComponent\IMessagePlugin, \DebugComponent\IRenderable {

    public function  __construct() {
        $this->databases = array();
        $this->queries = array();
    }

    public function setRenderer(\DebugComponent\IRenderer $renderer) {
        $this->renderer = $renderer;
    }

    public function getListenMessages() {
        return array('\DebugComponent\Message\Query', '\DebugComponent\Message\Database');
    }

    public function write(\DebugComponent\IMessage $message) {
        if ($message instanceof \DebugComponent\Message\Query) {
            $this->queries[] = $message;
        }

        if ($message instanceof \DebugComponent\Message\Database) {
            $this->databases[] = $message;
        }
    }

    public function getTitle() {
        return 'Databases';
    }

    public function getSubtitle() {
        $queriesCount = 0;
        foreach ($this->queries as $dsn => $queries) {
            $queriesCount += count($queries);
        }
        return count($this->databases) . ' / ' . $queriesCount;
    }

    public function render() {
        $data = new \DebugComponent\ParameterHolder();
        $data->set('databases', $this->databases);
        $data->set('queries', $this->queries);
        $data->set('title', $this->getTitle());
        $data->set('subtitle', $this->getSubtitle());
        return $this->renderer->render($data);
    }

    private $databases;
    private $queries;
    private $renderer;
}